package com.zf.bm.common.core.sys.web;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.zf.bm.common.core.shiro.utils.ShiroUtils;
import com.zf.bm.common.utils.Result;
import com.zf.bm.common.utils.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Slf4j
@RestController
public class ValidateCodeController {

    @Autowired
    private Producer producer;

    @RequestMapping("${adminPath}/jcaptcha.jpg")
    public void validateCode(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setValidateCode(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);

    }

    @RequestMapping("${adminPath}/jcaptchaOut")
    public Result validateCodeTimeOut(){
        log.warn("验证码已失效");
        ShiroUtils.validateCodeTimeOut(Constants.KAPTCHA_SESSION_KEY);
        return new Result(ResultStatus.SUCCESS.getCode());
    }
}
